package com.wen.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.wen.commonutils.ResultEntity;
import com.wen.servicebase.exception.BusinessException;
import com.wen.vod.service.VodService;
import com.wen.vod.util.InitVodClient;
import com.wen.vod.util.VodProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author：Win
 * @Date: 2021/6/11 14:58
 * @Description: 上传视频接口
 */
@RestController
@RequestMapping("/edu/vod/video")
public class VodController {
    @Resource
    private VodService vodService;

    /**
     * 上传视频到阿里云的方法
     *
     * @param file 需要上传的视频
     * @return 上传成功后的视频id
     */
    @PostMapping("/upload")
    public ResultEntity uploadVideo(MultipartFile file) {
        String videoId = vodService.uploadVideo(file);
        System.out.println(videoId);
        return ResultEntity.ok().data("videoId", videoId);
    }

    /**
     * 删除单个视频
     *
     * @param id 视频id
     * @return 成功或失败
     */
    @DeleteMapping("/delete/{id}")
    public ResultEntity deleteSingleAlyVideo(@PathVariable("id") String id) {
        vodService.deleteSingleAlyVideo(id);
        return ResultEntity.ok();
    }

    /**
     * 删除多个视频(因为一个课程对应多个章节,一个章节对应多个小节,
     * 每个小节对应一个视频,所以在删除章节或者整个课程时,需要用到此方法)
     *
     * @param ids 视频id集合
     * @return 成功或失败
     */
    @DeleteMapping("/delete/batch")
    public ResultEntity deleteMultiAlyVideo(@RequestParam("ids") List<String> ids) {
        vodService.deleteMultiAlyVideo(ids);
        return ResultEntity.ok();
    }

    /**
     * 获取阿里云视频播放凭证
     *
     * @param id 视频id
     * @return 播放凭证
     */
    @GetMapping("getPlayAuth/{id}")
    public ResultEntity getPlayAuth(@PathVariable("id") String id) {
        try {
//            创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(VodProperties.ACCESS_KEY_ID, VodProperties.ACCESS_KEY_SECRET);
//            创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
//            向request中设置id
            request.setVideoId(id);
//            得到response对象
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
//            获取凭证
            String playAuth = response.getPlayAuth();
            return ResultEntity.ok().data("playAuth", playAuth);
        } catch (Exception e) {
            throw new BusinessException("视频播放凭证获取失败");
        }

    }
}
